package com.ruili.framework.interceptor;

import com.ruili.framework.module.blacklist.service.BlackListService;
import com.ruili.framework.utils.ServletUtils;
import com.ruili.framework.utils.ip.IpUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Service
public class ErrorInterceptor implements HandlerInterceptor {

    @Autowired
    private BlackListService blackListService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (blackListService.checkIsBlackList()){
            ServletUtils.renderString(response,"["+ IpUtils.getRequestIpAddr() +"]在黑名单列表中");
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (response.getStatus() == 500) {
            ServletUtils.renderString(response,"页面报错");
        } else if (response.getStatus() == 404) {
            blackListService.matchBlackList();
            ServletUtils.renderString(response,"页面不存在");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
